import type { Router, LocationQueryRaw } from 'vue-router'
import NProgress from 'nprogress' // progress bar

import { useUserStore } from '@renderer/store'
import { isLogin } from '@renderer/utils/auth'

export default function setupUserLoginInfoGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    NProgress.start()
    const userStore = useUserStore()
    if (isLogin()) {
      if (userStore.role) {
        next()
      } else {
        await userStore.logout()
        next({
          name: 'login',
          query: {
            redirect: to.name,
            ...to.query
          } as LocationQueryRaw
        })
      }
    } else {
      if (to.name === 'login') {
        next()
        return
      } else {
        next({
          name: 'login',
          query: {
            redirect: to.name,
            ...to.query
          } as LocationQueryRaw
        })
      }
    }
  })
}
